Skip to content

767_count_domens#788

Open
vovanbravin wants to merge 3 commits into
devfrom
767_count_domens
Open

767_count_domens#788
vovanbravin wants to merge 3 commits into
devfrom
767_count_domens

Conversation

@vovanbravin
Copy link
Copy Markdown
Collaborator

No description provided.

@vovanbravin
Copy link
Copy Markdown
Collaborator Author

Запрещенные домены не добавлял проверку, так как есть уже критерий banned_words_in_lit, который уже проверяет это момент (тестировал).

Copy link
Copy Markdown
Collaborator

@HadronCollider HadronCollider left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Исправьте логику в #776 и подтяните изменения
После поставьте лейбл "need_review"

@github-actions github-actions Bot added the has conflicts if new merge has conflicts label Mar 13, 2026
@vovanbravin vovanbravin added need_review and removed has conflicts if new merge has conflicts labels Mar 13, 2026
@HadronCollider HadronCollider changed the base branch from 762_duplicate_literature_references to dev March 16, 2026 18:04
return start_index

def find_domains(self, sources: str):
pattern = r'(?:https?|ftp)?://([^/\s?#]+)'
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вынесите в поле класса

Comment on lines +185 to +188
if match and match.group(1):
self.literature_domains.append(match.group(1))
else:
self.literature_domains.append('') #чтобы можно было определить номер
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Сократите до 1 строки (тернарный оператор)

break
return start_index

def find_domains(self, sources: str):
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

смысла в этой функции как методе класса - 0 (он ещё и меняет состояние объекта, хотя вроде как должен просто найти домены) - проще regexp использовать в count_sources_*, и self.literature_domains.append делать там же (там будет и доступ к индексу)

if match and match.group(1):
self.literature_domains.append(match.group(1))
else:
self.literature_domains.append('') #чтобы можно было определить номер
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Чтобы определить номер, достаточно хранить его - вместе с доменом, иначе у вас есть список из 100 пустых строк (=много источников), потому что доменов среди нет нет

counter = Counter([text.lower() for text in self.literature_reference_text])
def checking_duplicate_sources(self, sources: list[str], max_count: int) -> list:
"""Функция нахождения дубликатов в определенных позициях"""
counter = Counter([text.lower() for text in sources])
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

замените лист на генератор - он будет работать быстрее и меньше займет памяти

Comment on lines +160 to +161
for text, count in counter.items():
if count >= 2:
positions_duplicates = [i + 1 for i, text_in_ref in enumerate(self.literature_reference_text) if text == text_in_ref.lower()]
if count >= max_count and text != '':
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Чтобы не делать на каждом шаге итерации сравнение text != '' - можно ещё на этапе формирования Counter не добавлять эти строки (например, фильтруя text.lower() for text in sources if text.strip())

def checking_duplicate_sources(self) -> list:
"""Функция нахождения дубликатов в источниках"""
counter = Counter([text.lower() for text in self.literature_reference_text])
def checking_duplicate_sources(self, sources: list[str], max_count: int) -> list:
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

добавьте для max_count значение по умолчанию (= исходная логика с дубликатами источников)

@github-actions github-actions Bot added the has conflicts if new merge has conflicts label May 4, 2026
Comment on lines 198 to 241
def count_sources_vkr(self, header):
literature_counter = 0
if not len(header["child"]):
return literature_counter
for child in header["child"]:
if child["text"].startswith('ПРИЛОЖЕНИЕ'):
break
# if re.search(f"дата обращения", child["text"].lower()):
literature_counter += 1
self.literature_reference_text.append(child["text"])
self.literature_reference_text.append((literature_counter, child["text"]))
domain_match = re.search(self.domain_pattern, child["text"], re.IGNORECASE)

if domain_match and domain_match.group(1):
self.literature_domains.append((literature_counter, domain_match.group(1)))

return literature_counter

def count_sources(self):
literature_counter = 0
start_page, end_page = self.search_literature_start_pdf()
for i in range(start_page, end_page + 1):
one_page = self.file.pdf_file.text_on_page[i].split('\n')
first_string = -1
last_string = len(one_page)

for j in range(len(one_page)):
one_str_lowercase = one_page[j].lower()
if re.search(self.name_pattern, one_str_lowercase):
first_string = j
break
for j in range(first_string, len(one_page)):
if re.search('приложение а[\n .]', one_page[j].lower()):
last_string = j
break

for ind in range(first_string + 1, last_string):
if re.match(f"{literature_counter + 1}.", one_page[ind]):
literature_counter += 1
self.literature_reference_text.append(one_page[ind])
self.literature_reference_text.append((literature_counter, one_page[ind]))
domain_match = re.search(self.domain_pattern, one_page[ind])
if domain_match and domain_match.group(1):
self.literature_domains.append((literature_counter, domain_match.group(1)))

return literature_counter
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

сделайте один итоговый метод, который будет поддерживать всё (и docx с вкр/лр и markdown) читая только текст (а не пдф)

никакого смысла в разделении логики нет

Comment on lines +181 to +184
for number, domain in sources:
if domain not in domain_to_numbers:
domain_to_numbers[domain] = []
domain_to_numbers[domain].append(number)
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

достаточно сделать

    for number, domain in sources:
        domain_to_numbers.setdefault(domain, []).append(number)

duplicates_domains = self.checking_duplicate_sources(self.literature_domains, self.max_count_domains)
references, ref_sequence = self.search_references(start_literature_par)
all_numbers = set(range(1, number_of_sources + 1))
if len(references.symmetric_difference(all_numbers)) == 0:
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Сделайте логику ниже единой и непрерываемой на середине

  • проверяется одно условие -> по нему добавляется фидбек -> проверяется следующее условие -> и так далее
  • после всего -> return+answer'a было только два
    • иначе сейчас одна проверка делает return - остальные не запускаются

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Changes requested has conflicts if new merge has conflicts

Projects

None yet

2 participants